package com.android.fragmentdemo.definervlayoutmanager;
import android.graphics.Rect;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class StudyLayoutManager2 extends RecyclerView.LayoutManager {
    private static final String TAG = "StudyLayoutManager";
    private final int margins;
    private int mSumDy = 0;
    private int mTotalHeight = 0;
    private final SparseArray<Rect> allFrameRect = new SparseArray<>();

    public StudyLayoutManager2(int margins) {
        this.margins = margins;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public boolean isAutoMeasureEnabled() {
        Log.d(TAG, "isAutoMeasureEnabled");
        //这里返回true,RecyclerView设置高为wrap_content时,才会显示item;否则高度只有设置match_parent才会显示item.
        return true;
    }

    @Override
    public void onMeasure(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state, int widthSpec, int heightSpec) {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
        Log.d(TAG, "public void onMeasure");
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        Log.d(TAG, "public void onLayoutChildren");
        super.onLayoutChildren(recycler, state);
        initialItems(recycler);
        removeAllViews();
        detachAndScrapAttachedViews(recycler);
//        int offsetX = 0;
//        int offsetY = 0;
//        int extraHeight = 0;
//        final int itemCount = getItemCount();
//        //Log.d("StudyLayoutManager", "itemCount:" + itemCount);
//        for (int i = 0; i < itemCount; i++) {
//            View child = recycler.getViewForPosition(i);
//            addView(child);
//            measureChildWithMargins(child, 0, 0);
//            int measuredWidth = getDecoratedMeasuredWidth(child) + margins;
//            int measuredHeight = getDecoratedMeasuredHeight(child);
//            Rect rect = allFrameRect.get(i);
//            if (rect == null) {
//                rect = new Rect();
//            }
//            if (offsetX + measuredWidth > getWidth()) {
//                Log.d("StudyLayoutManager", "i:" + i);
//                offsetY += measuredHeight + margins;
//                rect.set(margins, offsetY, margins + measuredWidth, offsetY + measuredHeight);
//                offsetX = measuredWidth + margins;
//            } else {
//                int extraValue = (i == 0) ? margins : 0;
//                rect.set(offsetX + extraValue, offsetY, offsetX + extraValue + measuredWidth, offsetY + measuredHeight);
//                if (i == 0) {
//                    offsetX += margins;
//                }
//                offsetX += measuredWidth;
//            }
//            allFrameRect.put(i, rect);
//            layoutDecorated(child, rect.left, rect.top, rect.right, rect.bottom);
//            if (itemCount - 1 == i) {
//                extraHeight = measuredHeight;
//            }
//        }
//        //如果所有子view的高度和没有填满RecyclerView,则将高度设置为RecyclerView高度
//        offsetY += extraHeight;
//        mTotalHeight = Math.max(offsetY, getVerticalSpace());

        final int itemCount = getItemCount();
        for (int i = 0; i < itemCount; i++) {
            Rect rect = allFrameRect.get(i);
            if (rect.top > getVerticalSpace()) {
                Log.d(TAG, "i--" + i);
                break;
            }
            View view = recycler.getViewForPosition(i);
            addView(view);
            measureChildWithMargins(view, 0, 0);
            Log.d(TAG, "rect.top--" + rect.top);
            layoutDecorated(view, rect.left, rect.top, rect.right, rect.bottom);
        }
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int travel = dy;
        if (mSumDy + dy < 0) {
            //滑动到顶部
            travel = -mSumDy;
        } else if (mSumDy + dy > mTotalHeight - getVerticalSpace()) {
            //滑动到底部
            travel = mTotalHeight - getVerticalSpace() - mSumDy;
        }
        mSumDy += travel;
        //offsetChildrenVertical(-travel);
        recyclerViewFillView(recycler);
        return travel;
    }

    @Override
    public boolean canScrollVertically() {
        return true;
    }

    private void recyclerViewFillView(RecyclerView.Recycler recycler) {
        detachAndScrapAttachedViews(recycler);

        Rect rect = new Rect(0, mSumDy, getWidth(), mSumDy + getHeight());
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child != null) {
                Rect childRect = allFrameRect.get(i);
                if (!Rect.intersects(rect, childRect)) {
                    //移除屏幕外的
                    removeAndRecycleView(child, recycler);
                }
            }
        }

        for (int i = 0; i < getItemCount(); i++) {
            Rect scrapRect = allFrameRect.get(i);
            if (Rect.intersects(rect, scrapRect)) {
                //从回收池里拿
                View scrap = recycler.getViewForPosition(i);
                measureChildWithMargins(scrap, 0, 0);
                addView(scrap);
                layoutDecorated(scrap, scrapRect.left, scrapRect.top - mSumDy, scrapRect.right, scrapRect.bottom - mSumDy);
            }
        }
    }

    private int getVerticalSpace() {
        return getHeight() - getPaddingTop() - getPaddingBottom();
    }

    private void initialItems(RecyclerView.Recycler recycler) {
        int offsetX = margins;
        int offsetY = margins;
        int extraHeight = 0;
        final int itemCount = getItemCount();
        for (int i = 0; i < itemCount; i++) {
            View child = recycler.getViewForPosition(i);
            addView(child);
            measureChildWithMargins(child, 0, 0);
            int measuredWidth = getDecoratedMeasuredWidth(child);
            int measuredHeight = getDecoratedMeasuredHeight(child);
            Log.d(TAG, "measuredHeight--measuredHeight--" + measuredHeight);
            Rect rect = allFrameRect.get(i);
            if (rect == null) {
                rect = new Rect();
            }
            if (offsetX + measuredWidth > getWidth()) {
                Log.d(TAG, "i:" + i);
                offsetX = margins;
                offsetY += measuredHeight + margins;
            }
            rect.set(offsetX, offsetY, offsetX + measuredWidth, offsetY + measuredHeight);
            offsetX += margins + measuredWidth;
            allFrameRect.put(i, rect);
            if (itemCount - 1 == i) {
                extraHeight = measuredHeight;
            }
        }
        //如果所有子view的高度和没有填满RecyclerView,则将高度设置为RecyclerView高度
        offsetY += extraHeight;
        //此次margins为底部边距值
        mTotalHeight = Math.max(offsetY, getVerticalSpace()) + margins;

        for (int i = 0; i < itemCount; i++) {
            removeAndRecycleView(recycler.getViewForPosition(i), recycler);
        }
    }
}
